import axios from 'axios'
import { useUserStore } from '../stores/user'
import { ElMessage } from 'element-plus'

// Create axios instance
const instance = axios.create({
    // Remove baseURL, use relative paths
    timeout: 15000,
    headers: {
        'Content-Type': 'application/json'
    }
})

// Request interceptor
instance.interceptors.request.use(
    config => {
        // Get the latest token from localStorage before each request
        const token = localStorage.getItem('token')
        if (token) {
            // Add debugging log
            console.log('Sending request with token:', token.substring(0, 10) + '...')
            config.headers.Authorization = `Bearer ${token}`
        } else {
            console.log('Request is not carrying a token, the user may not be logged in')
        }
        return config
    },
    error => {
        console.error('Request sending failed:', error)
        return Promise.reject(error)
    }
)

// Response interceptor
instance.interceptors.response.use(
    response => response,
    error => {
        // Add detailed error log
        console.error('API request error:', {
            status: error.response?.status,
            url: error.config?.url,
            method: error.config?.method,
            data: error.config?.data, // Request data
            responseData: error.response?.data, // Response data
            headers: error.config?.headers, // Request headers
            error: error.message
        })

        // Get specific error message
        const errorMessage = error.response?.data?.message || 'Request failed, please try again later'
        const statusCode = error.response?.status
        const requestUrl = error.config?.url || 'Unknown URL'

        // Check if it is a 404 error related to project or task evaluation
        const isEvaluationRequest = requestUrl && (
            requestUrl.includes('/evaluation') ||
            requestUrl.includes('/evaluate')
        )

        // Handle different error situations based on the status code
        switch (statusCode) {
            case 400:
                console.log('Invalid request parameters:', errorMessage)
                break
            case 401:
                console.log(`Authorization failed (${requestUrl}):`, errorMessage)
                console.log('Current token:', localStorage.getItem('token'))

                if (!requestUrl.includes('/api/auth/info')) {
                    const userStore = useUserStore()
                    userStore.handleAuthError()
                } else {
                    console.log('Ignoring 401 error for user information API to prevent circular redirection')
                }
                break
            case 403:
                console.log(`Insufficient permissions (${requestUrl}):`, errorMessage)
                ElMessage.error('Insufficient permissions to perform this operation')
                break
            case 404:
                console.log(`Requested resource not found (${requestUrl}):`, errorMessage)
                // For evaluation-related 404 errors, do not display a global error message
                if (!isEvaluationRequest) {
                    ElMessage.error('Requested resource not found')
                } else {
                    console.log('Evaluation-related 404 error, normal situation, not displaying error message')
                }
                break
            case 500:
                console.log(`Server error (${requestUrl}):`, errorMessage)
                ElMessage.error('Server error, please try again later')
                break
            default:
                if (error.message === 'Network Error') {
                    console.log('Network connection error, please check your network connection or server status')
                    ElMessage.error('Network connection error, please check your network connection or server status')
                } else {
                    console.log(`Unknown error (${requestUrl}):`, error)
                }
        }

        if (error.response?.data) {
            error.data = error.response.data
        }

        return Promise.reject(error)
    }
)

export default instance